package ltd.bugs.cute.httpclient.scheduler;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ltd.bugs.cute.common.spring.ApplicationContextHolder;
import ltd.bugs.cute.httpclient.HttpComponentsRequestFactory;
import ltd.bugs.cute.httpclient.config.HttpClientConfig;
import ltd.bugs.cute.scheduler.spi.Scheduler;

/**
 * 定时清掉无效连接和超过等待时间的空闲连接
 * 
 * @author zhengzhq
 *
 */
public class HttpClientConnectionEvictor implements Scheduler {

  private static Logger logger = LoggerFactory.getLogger(HttpClientConnectionEvictor.class);
  private static HttpClientConfig config = ApplicationContextHolder.getBean(HttpClientConfig.class);

  @Override
  public String getExpression() {
    // 默认30秒执行一次
    return config.getConnectionMgrCronExpression();
  }

  @Override
  public void process() {
    if (logger.isDebugEnabled()) {
      logger.debug("start evict http connections");
    }
    // 关闭失效的连接
    HttpComponentsRequestFactory.getConnectionManager().closeExpiredConnections();
    // 关闭空闲的连接
    HttpComponentsRequestFactory.getConnectionManager()
        .closeIdleConnections(config.getConnectionIdleTime(), TimeUnit.MICROSECONDS);
    if (logger.isDebugEnabled()) {
      logger.debug("end evict http connections");
    }
  }
}
